package main

import (
	"context"
	"distributed/registry"
	"fmt"
	"log"
	"net/http"
)

func main() {
	registry.SetupRegistryService()

	http.Handle("/services", &registry.Service{})

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	var srv http.Server
	srv.Addr = ":" + registry.ServerPort

	runServer(&srv, cancel)

	runShutdownListener(ctx, registry.RegistryService, &srv, cancel)

	<-ctx.Done()
	fmt.Println("Shutting down registry service")
}

func runServer(srv *http.Server, cancel context.CancelFunc) {
	go func() {
		log.Println(srv.ListenAndServe())
		cancel()
	}()
}

func runShutdownListener(ctx context.Context, serviceName registry.ServiceName, srv *http.Server,
	cancel context.CancelFunc) {
	go func() {
		fmt.Printf("%v started, press any key to stop.\n", serviceName)
		var s string
		fmt.Scanln(&s)
		srv.Shutdown(ctx)
		cancel()
	}()
}
